#include "login.h"
#include "ui_login.h"
#include "global_var.h"
#include "data_bean.h"
#include "registerdialog.h"
#include "dashboard.h"

#include <QMessageBox>

Login::Login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);
}

Login::~Login()
{
    delete ui;
}

int Login::check_login(QString id, QString password) {
    for(int i = 0; i < users.length(); i++) {
        if(users.at(i).getId() == id && users.at(i).getPassword() == password)
            return i;
    }
    return -1;
}

void Login::login_init(int index)
{
    current_user = users[index];

    QVector<Group> cur_group;
    for(int i=0; i < groups.size(); i++) {
        if(groups[i].getGroup_manager() == current_user.getId()) {
            cur_group.push_back(groups[i]);
            continue;
        }

        // in group member
        QVector<QString> tmp = groups[i].getMembers();
        for(QString member_name : tmp) {
            if(member_name == current_user.getId()) {
                cur_group.push_back(groups[i]);
                break;
            }
        }
    }
    current_groups = cur_group;

    QVector<Task> cur_task;
    for(int i=0; i < tasks.size(); i++) {
        if(tasks[i].getTask_owner() == current_user.getId()) {
            cur_task.push_back(tasks[i]);
            continue;
        }

        // in task member
        QMap<QString, QString> tmp = tasks[i].getMember_hand_in_state_map();
        for(auto key : tmp.keys()) {
            if(key == current_user.getId()) {
                cur_task.push_back(tasks[i]);
                break;
            }
        }
    }
    current_tasks = cur_task;
}

void Login::on_btn_login_clicked()
{
    int index = check_login(ui->input_uid->text(), ui->input_pwd->text());
    if(index != -1) {
        // 登陆成功，初始化用户数据
        login_init(index);

        QMessageBox::information(this, tr("Success"), tr("登陆成功"), QMessageBox::Yes);

        Dashboard *dashboard_dialog = new Dashboard();
        dashboard_dialog->show();

        this->close();
    } else {
        QMessageBox::information(this, tr("Error"), tr("用户名/密码错误"), QMessageBox::Yes);
    }
}

void Login::on_pushButton_clicked()
{
    RegisterDialog *dialog = new RegisterDialog();
    dialog->show();
}
